﻿using ELF.Modules;
using Microsoft.EntityFrameworkCore;
using ProductService.Data;
using ProductService.Services;

namespace ProductService;

[DependsOn(typeof(ElfDddDomainModule))]
[DependsOn(typeof(ElfDddDataModule))]
[DependsOn(typeof(ElfdddWebApiModule))]
public class ProductServiceModule : BaseModule
{
    public override async Task ConfigureServicesAsync(IHostApplicationBuilder builder)
    {
        builder.Services.AddControllers();
        // Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
        builder.Services.AddOpenApi();
        builder
            .Services.AddAuthentication()
            .AddKeycloakJwtBearer(
                serviceName: "keycloak",
                realm: "overflow",
                options =>
                {
                    options.Audience = "overflow";
                    // if (builder.Environment.IsDevelopment())
                    // {
                    options.RequireHttpsMetadata = false;
                    // }
                }
                                 );

        builder.Services.AddAppDbContext<ApplicationDbContext>(
            (sp, options) =>
            {
                // options.AddInterceptors()
                options.UseNpgsql(
                    builder.Configuration.GetConnectionString("productDb") ?? "productDb"
                                 );
            }
                                                              );

        builder.EnrichNpgsqlDbContext<ApplicationDbContext>(configureSettings: settings =>
        {
            settings.DisableRetry = false;
            settings.CommandTimeout = 30;
        });

        builder.Services.AddMemoryCache();
        builder.Services.AddScoped<TagService>();

        await base.ConfigureServicesAsync(builder);
    }

    public override async Task InitializeAsync(IApplicationBuilder app)
    {
        using (var scope = app.ApplicationServices.CreateScope())
        {
            var services = scope.ServiceProvider;
            try
            {
                var context = services.GetRequiredService<ApplicationDbContext>();
                await SeedData.InitializeAsync(context);
            }
            catch (Exception ex)
            {
                var logger = services.GetRequiredService<ILogger<Program>>();
                logger.LogError(ex, "种子数据初始化失败");
            }
        }

        await base.InitializeAsync(app);
    }
}
